<template>
  <div class="container">
    <!-- Left Panel -->
    <div class="left-panel">
      <div class="network-info">
        <div class="info-item">
          <h3>Network Name</h3>
          <select v-model="networkName" @change="updateNetworkName" class="network-select">
            <option v-for="(name, index) in networkOptions" :key="index" :value="name">
              {{ name }}
            </option>
          </select>
          <button class="scan-button" @click="scanNetwork">
            Scan Network
          </button>
        </div>
        <div class="info-item">
          <h3>Your Device Name</h3>
          <div class="device-name-input">
            <input type="text" v-model="deviceName" @change="updateDeviceName" class="device-name-field">
          </div>
        </div>
      </div>

      <div class="users-list">
        <div class="users-list-header">
          <h3>Available Users</h3>
          <button class="refresh-button" @click="refreshUsers" :disabled="!networkName">
            Refresh
          </button>
        </div>
        <div v-for="user in users" :key="user.name" :class="['user-item', { active: selectedUser?.name === user.name }]"
          @click="selectUser(user)">
          <span class="user-name">{{ user.name }}</span>
        </div>
      </div>
    </div>

    <!-- Right Panel -->
    <div class="right-panel">
      <div class="connected-user">
        <h3>Connected User</h3>
        <p v-if="selectedUser">{{ selectedUser.name }}</p>
        <p v-else>No user selected</p>
      </div>

      <div class="file-transfer">
        <button class="select-file-btn" @click="handleFileSelect" :disabled="!selectedUser"
          :class="{ 'has-file': selectedFile }">
          <span v-if="!selectedFile">📁 Select File</span>
        </button>

        <div class="transfer-log">
          <h3>Transfer Log</h3>
          <div class="log-content">{{ transferLog }}</div>
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts">
import { invoke } from '@tauri-apps/api/core';
import { listen, Event } from '@tauri-apps/api/event';
import { defineComponent, ref, onMounted } from 'vue'
import { open, message } from '@tauri-apps/plugin-dialog';

interface User {
  name: string,
  ip: string,
}

export default defineComponent({
  name: 'App',
  setup() {
    const networkName = ref<string>('127.0.0.1')
    const networkOptions = ref<string[]>([])
    const deviceName = ref<string>('')
    const users = ref<User[]>([])
    const selectedUser = ref<User | null>(null)
    const transferLog = ref<string>('')
    const selectedFile = ref<File>()

    const scanNetwork = async () => {
      const data = await invoke<string[]>('get_available_ips');
      networkOptions.value = data;
      networkName.value = networkOptions.value[0];
    }

    const updateNetworkName = async () => {
      // 向后端发送更新后的网络名称
      console.log('Updated network name:', networkName.value)
      await invoke('change_target_ip', { 'targetIp': networkName.value });
      await message('已成功更改网络环境', { title: '操作成功', kind: 'info' });
      // 这里添加实际的后端调用
    }


    // User selection function
    const selectUser = (user: User) => {
      selectedUser.value = user
      // Implementation for connection will be handled by Tauri backend
    }

    // Device name update function
    const updateDeviceName = async () => {
      // Implementation will be handled by Tauri backend to update device name
      console.log('Updated network name:', deviceName.value)
      await invoke('rename_discover', { 'newName': deviceName.value });
      await message('已成功更改设备名字', { title: '操作成功', kind: 'info' });
    }


    const handleFileSelect = async () => {
      try {
        const file = await open({
          multiple: false,
          directory: false,
          filters: [{ name: 'All Files', extensions: ['*'] }]
        }); // 根据实际返回类型调整

        if (!file) {
          printMessage('File selection cancelled')
          return
        }
        console.log("file: ", file);
        await invoke('start_file_transfer', { filePath: file, targetIp: selectedUser.value?.ip[0] })

      } catch (error) {
        console.error('Error selecting file:', error)
        printMessage(`Error: ${error}`)
      }
    }

    const refreshUsers = async () => {
      try {
        const freshUsers = await invoke<User[]>('get_users');
        users.value = freshUsers;
        printMessage(`Users refreshed at ${new Date().toLocaleTimeString()}`);
      } catch (error) {
        console.error('Error refreshing users:', error);
        printMessage(`Error refreshing users: ${error}`);
      }
    }

    const initWindow = async () => {
      try {
        let instance_name = await invoke<string>('get_instance_name');
        deviceName.value = instance_name;
        scanNetwork()
      } catch (error) {
        console.error('Error initializing window:', error)
        printMessage(`Error initializing window: ${error}\n`)
      }
    }

    const printMessage = async (message: string) => {
      transferLog.value = message + '\n' + transferLog.value;
    }

    onMounted(() => {
      listen('clock_signal', () => {
        scanNetwork();
        refreshUsers();
      })
      listen('print', (event: Event<string>) => {
        printMessage(event.payload);
      })

      initWindow()
    })

    return {
      networkName,
      deviceName,
      users,
      selectedUser,
      transferLog,
      networkOptions,
      scanNetwork,
      updateNetworkName,
      selectUser,
      handleFileSelect,
      updateDeviceName,
      refreshUsers,
      selectedFile
    }
  }
})
</script>

<style scoped>
.select-file-btn {
  position: relative;
  padding: 12px 20px;
  background: #1976d2;
  color: white;
  border: none;
  border-radius: 8px;
  cursor: pointer;
  font-size: 16px;
  transition: all 0.2s ease;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.select-file-btn:hover:not(:disabled) {
  background: #1565c0;
  transform: translateY(-1px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
}

.select-file-btn:active:not(:disabled) {
  transform: translateY(0);
}

.select-file-btn.has-file {
  background: #4CAF50;
}

.select-file-btn.has-file:hover:not(:disabled) {
  background: #45a049;
}

.file-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.file-size {
  font-size: 0.9em;
  opacity: 0.8;
}

.select-file-btn:disabled {
  background: #bdbdbd;
  cursor: not-allowed;
  opacity: 0.7;
}

.select-file-btn:disabled:hover {
  transform: none;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.network-select {
  width: 100%;
  padding: 8px;
  margin: 5px 0;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
}

.scan-button {
  width: 100%;
  padding: 8px;
  margin-top: 10px;
  background: #4CAF50;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
}

.scan-button:hover {
  background: #45a049;
}

.container {
  display: flex;
  height: 100vh;
  padding: 20px;
  gap: 20px;
}

.left-panel,
.right-panel {
  flex: 1;
  background: #ffffff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.network-info {
  margin-bottom: 20px;
}

.info-item {
  margin-bottom: 15px;
}

.info-item h3 {
  font-size: 14px;
  color: #666;
  margin-bottom: 5px;
}

.info-item p {
  font-size: 16px;
  color: #333;
  font-weight: 500;
}

.device-name-input {
  margin-top: 5px;
}

.device-name-field {
  width: 100%;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 16px;
  color: #333;
  transition: border-color 0.2s;
}

.device-name-field:focus {
  outline: none;
  border-color: #1976d2;
}

.users-list {
  margin-top: 20px;
}

.user-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  margin: 8px 0;
  border-radius: 6px;
  background: #f5f5f5;
  cursor: pointer;
  transition: background-color 0.2s;
}

.user-item:hover {
  background: #eee;
}

.user-item.active {
  background: #e3f2fd;
}

.user-status {
  width: 8px;
  height: 8px;
  border-radius: 50%;
}

.user-status.online {
  background: #4caf50;
}

.user-status.offline {
  background: #9e9e9e;
}

.connected-user {
  margin-bottom: 20px;
}

.select-file-btn {
  width: 100%;
  padding: 12px;
  background: #1976d2;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 16px;
  transition: background-color 0.2s;
}

.select-file-btn:hover {
  background: #1565c0;
}

.select-file-btn:disabled {
  background: #bdbdbd;
  cursor: not-allowed;
}

.transfer-log {
  margin-top: 20px;
}

.log-content {
  margin-top: 10px;
  padding: 10px;
  background: #f5f5f5;
  border-radius: 4px;
  height: 200px;
  overflow-y: auto;
  font-family: monospace;
  font-size: 14px;
  white-space: pre-wrap;
}

.users-list-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.refresh-button {
  padding: 6px 12px;
  background: #2196F3;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  transition: background-color 0.2s;
  font-size: 14px;
}

.refresh-button:hover {
  background: #1976D2;
}

.refresh-button:disabled {
  background: #BBDEFB;
  cursor: not-allowed;
}
</style>